//
//  AppDelegate+UMPush.m
//  GainInvest
//
//  Created by 王玉龙 on 17/3/16.
//  Copyright © 2017年 longlong. All rights reserved.
//

#import "AppDelegate+UMPush.h"
#import "MainTabBarController.h"
#import "MessageListViewController.h"

#import "ECDevice.h"
#import <UMSocialCore/UMSocialCore.h>

#import <UMMobClick/MobClick.h>



@implementation AppDelegate (UMPush)

- (void)umPushApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //本地创建一个消息表
    [MessageTableDAO createMessageTable];
    
    //注册APP key 启动支持Https
    [UMessage startWithAppkey:@"58cb67d8677baa551f00047a" launchOptions:launchOptions httpsEnable:YES];
    
    //注册通知
    [UMessage registerForRemoteNotifications];
    [UMessage openDebugMode:YES];
    [UMessage setAutoAlert:NO];

    
    {
        // 友盟统计
        NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        [MobClick setAppVersion:version];

        
        UMConfigInstance.appKey = @"58cb67d8677baa551f00047a";
        UMConfigInstance.channelId = @"App Store";
        [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    }
    
    
    
    
    [self perfectUMSocialManagerInfo];
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000

    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate=self;
    UNAuthorizationOptions types10 = UNAuthorizationOptionBadge|UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error)
    {
        NSLog(@"granted ====== %d",granted);
        NSLog(@"domain ====== %@",error.domain);
        
        if (granted)
        {
            //点击允许
            
        }
        else
        {
            //点击不允许
        }
    }];
#endif



    
    //打开日志，方便调试
//    [UMessage setLogEnabled:YES];
}


- (void)perfectUMSocialManagerInfo
{
    [[UMSocialManager defaultManager] openLog:YES];
    
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"58cb67d8677baa551f00047a"];
    [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
    
    UMSocialLogInfo(@"UMeng social version: %@", [UMSocialGlobal umSocialSDKVersion]);
    
    
    //设置微信的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxab7216f0d45a0485" appSecret:@"81adf968f08fc8c7d416ec300ddd264f" redirectURL:@"http://sureapi.dt87.cn/pay/notify_url"];
    
    //设置分享到QQ互联的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"101387525"  appSecret:nil redirectURL:@"http://sureapi.dt87.cn/pay/notify_url"];
    
}

// 注册 deviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString *strDeviceToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]                  stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
    
    //向友盟注册该设备的deviceToken，便于发送Push消息
    [UMessage registerDeviceToken:deviceToken];
    NSLog(@"UMessage registerDeviceToken ======= %@",strDeviceToken);
    
    
    [[ECDevice sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"error ====== %@",error);
}

//接收通知
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    NSDictionary * userInfo = notification.request.content.userInfo;
    NSLog(@"notification ====== %@",userInfo);

    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        //应用处于前台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        //应用处于前台时的本地推送接受
        [self showAlertWithInfo:userInfo];
    }
    else
    {
        //应用处于前台时的本地推送接受
        [self showAlertWithInfo:userInfo];
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    NSLog(@"response ====== %@",userInfo);

    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        [self lookNotificationDetaileWithInfo:userInfo IsStore:NO];
    }
    else
    {
        //应用处于后台时的本地推送接受
        [self lookNotificationDetaileWithInfo:userInfo IsStore:NO];
    }
}
#endif


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    completionHandler(UIBackgroundFetchResultNewData);
    
    [UMessage didReceiveRemoteNotification:userInfo];
    
    NSLog(@"userInfo 213====== %@",userInfo);
    
    
    if (application.applicationState == UIApplicationStateActive)
    {
        [self showAlertWithInfo:userInfo];
    }
    else if (application.applicationState == UIApplicationStateInactive)
    {
        [self lookNotificationDetaileWithInfo:userInfo IsStore:NO];
        
    }
    else if (application.applicationState == UIApplicationStateBackground)
    {
        // 应用在后台。当后台设置aps字段里的 content-available 值为 1 并开启远程通知激活应用的选项
        
        [self lookNotificationDetaileWithInfo:userInfo IsStore:NO];
    }
    
}



- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"userInfo ====== %@",userInfo);

    [UMessage didReceiveRemoteNotification:userInfo];
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
    {
        //处于前台
        [self showAlertWithInfo:userInfo];
    }
    else
    {
        [self lookNotificationDetaileWithInfo:userInfo IsStore:NO];
    }
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
    {
        //处于前台
        [self showAlertWithInfo:notification.userInfo];
    }
    else
    {
        [self lookNotificationDetaileWithInfo:notification.userInfo IsStore:NO];
    }
}

#pragma mark - Handle Method

- (void)showAlertWithInfo:(NSDictionary *)userInfo
{
    MessageModel *messageModel = [MessageModel modelObjectWithDictionary:userInfo];
    [MessageTableDAO insertContact:messageModel];
    [self getUnReadCount];
    
    
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"通知" message:messageModel.body preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"忽略" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action){}];
    
    UIAlertAction *loginAction = [UIAlertAction actionWithTitle:@"去查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                  {
                                      [self lookNotificationDetaileWithInfo:messageModel IsStore:YES];
                                  }];
    
    [actionSheet addAction:cancelAction];
    [actionSheet addAction:loginAction];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:actionSheet animated:YES completion:nil];
}

- (void)lookNotificationDetaileWithInfo:(id)userInfo IsStore:(BOOL)isStore
{
    [MainTabBarController setSelectedIndex:3];
    
    if ([userInfo isKindOfClass:[NSDictionary class]])
    {
        userInfo = [MessageModel modelObjectWithDictionary:userInfo];
    }
    
    if (isStore == NO)
    {
        [MessageTableDAO insertContact:userInfo];
        [self getUnReadCount];
    }
    
    //消息列表
    MessageListViewController *messageListVC = [[MessageListViewController alloc]init];
    messageListVC.hidesBottomBarWhenPushed = YES;
    UINavigationController *nav = [MainTabBarController shareMainController].selectedViewController;
    [nav pushViewController:messageListVC animated:NO];
}

- (void)getUnReadCount
{
    [MessageTableDAO getUnReadMessageCountCompletionBlock:^(NSUInteger count) {}];
}

@end
